<template>
  <div class="logic-flow-container">
    <div class="connection_pool">
      <el-select v-model="dataSourceName" placeholder="请选择连接池" @change="handleChange">
        <el-option
          v-for="item in fieldoptions"
          :key="item.id"
          :label="item.aliasName || item.dataSourceName"
          :value="item.id!"
        />
      </el-select>
      <div class="indicator_tree" style="overflow: auto">
        <el-tree
          ref="treeRef"
          :data="domainTreeData"
          node-key="id"
          default-expand-all
          :props="defaultProps"
          show-checkbox
          :check-strictly="true"
          @check-change="handleTreeChange"
        />
      </div>
    </div>
    <div class="logic-flow-main">
      <div ref="logicFlowRef" class="logic-flow" />
      <Setting
        class="logic-flow-setting"
        :data="nodeData!"
        :lf="lf"
        :type="settingType"
        :indicator-id="indicatorId"
        :indicator-ids="indicatorIds"
        @dataFetched="handleDataFetched"
      />
      <NodePanel :lf="lf" />
    </div>
    <!-- 当lf有值 才能注册事件 -->
    <Control
      v-if="lf"
      :lf="lf"
      :parameter="tableListParameter"
      :dataSourceName="dataSourceName"
      :ids="indicatorIds"
    />
    <!-- @showCreateIndicator="showCreateIndicatorDialog" -->
  </div>
</template>
<script lang="ts">
export default { name: "InsertIndicator" };
</script>
<script setup lang="ts">
import LogicFlow from "@logicflow/core";
import "@logicflow/core/lib/style/index.css";
import "@logicflow/extension/lib/style/index.css";
import Control from "./components/control.vue";
import Setting from "./components/setting.vue";
import NodePanel from "./components/nodePanel.vue";
import { SettingType } from "@/types/logic-flow";
import { registeNode, registerKeyboard } from "./index";
import IndicatorManageAPI, {
  DataSourceList,
  TableListParameter,
} from "@/api/strategy/strategy-index-database";
import indicatorDomainAPI, {
  DomainGroupsTreeReponse,
  DomainGroupInsertParameter,
} from "@/api/indicationManage/domain";
import type { TreeInstance } from "element-plus";

const treeRef = ref<TreeInstance>();
const logicFlowRef = ref<HTMLDivElement>();
const nodeData = ref<LogicFlow.NodeData | LogicFlow.EdgeData>(); // 节点数据
const settingType = ref<SettingType>("all");
let lf: LogicFlow;
const fieldoptions = ref<DataSourceList[]>();
const dataSourceName = ref();
const tableListParameter = reactive<TableListParameter>({});
const domainGroupInsertParameter = reactive<DomainGroupInsertParameter>({});
const defaultProps = {
  children: "children",
  label: "label",
  disabled: "disabled",
};

const domainTree = ref<DomainGroupsTreeReponse>();
// 新增：用于存储转换后的数据
const domainTreeData = ref<any[]>([]);

const getSettingInfo = (data: LogicFlow.NodeData | LogicFlow.EdgeData) => {
  switch (data.type) {
    case "all":
      break;
    case "indicator":
      nodeData.value = data;
      settingType.value = data.type;
      break;
    case "add_operate":
      nodeData.value = data;
      settingType.value = data.type;
      break;
    case "cut_operate":
      nodeData.value = data;
      settingType.value = data.type;
      break;
    case "multiply_operate":
      nodeData.value = data;
      settingType.value = data.type;
      break;
    case "except_operate":
      nodeData.value = data;
      settingType.value = data.type;
      break;
    case "greaterThan_operate":
      nodeData.value = data;
      settingType.value = data.type;
      break;
    case "greaterThanOrEqual_operate":
      nodeData.value = data;
      settingType.value = data.type;
      break;
    case "lessThan_operate":
      nodeData.value = data;
      settingType.value = data.type;
      break;
    case "lessThanOrEqual_operate":
      nodeData.value = data;
      settingType.value = data.type;
      break;
    case "indicatorConfig_operate":
      nodeData.value = data;
      settingType.value = data.type;
      break;
    case "indicator_output":
      nodeData.value = data;
      settingType.value = data.type;
      break;
  }
};

const indicatorId = ref();

/**
 * @description 注册事件
 */
const initEvent = (lf: LogicFlow) => {
  lf.on("blank:click", (e) => {
    settingType.value = "all";
  });
  lf.on("node:mousedown", ({ data }) => {
    if (data.type === "indicator") {
      indicatorId.value = data.properties?.treeNodeId;
    }
    lf.selectElementById(data.id, false);
    getSettingInfo(data);
  });
  lf.on("edge:click", ({ data }) => {
    lf.selectElementById(data.id, false);
    getSettingInfo(data);
  });
  lf.on("connection:not-allowed", (data) => {
    ElMessage.error(data.msg);
    return false;
  });
  lf.on("node:dnd-add", ({ data }) => {
    lf.selectElementById(data.id, false);
    getSettingInfo(data);
    lf.container.focus();
  });
  lf.on("edge:add", ({ data }) => {
    if (!lf.graphModel) {
      return;
    }
    const sourceNode = lf.graphModel.getNodeById
      ? lf.graphModel.getNodeById(data.sourceNodeId)
      : lf.graphModel.nodeModelMap.get(data.sourceNodeId);

    const targetNode = lf.graphModel.getNodeById
      ? lf.graphModel.getNodeById(data.targetNodeId)
      : lf.graphModel.nodeModelMap.get(data.targetNodeId);

    if (!sourceNode || !targetNode) {
      return;
    }

    const validTargetTypes = [
      "left_join",
      "right_join",
      "inner_join",
      "full_join",
      "indicator_output",
    ];
    if (sourceNode && targetNode) {
      if (validTargetTypes.includes(targetNode.type)) {
        transferData(sourceNode, targetNode);
        // 监听源节点的数据变化
        watch(
          () =>
            sourceNode.getProperties().tableData ||
            sourceNode.getProperties.related_fields1 ||
            sourceNode.getProperties.related_fields2,
          (newData: any) => {
            transferData(sourceNode, targetNode);
          },
          {
            deep: true,
          }
        );
      }
    }
  });
};

const transferData = (sourceNode: any, targetNode: any) => {
  // 获取 sourceNode 的数据
  const sourceProperties = sourceNode.getProperties();
  // 获取 targetNode 的现有数据
  const targetProperties = targetNode.getProperties();
  const validTargetTypes = ["left_join", "right_join", "inner_join", "full_join"];
  // 新增：如果源节点是 left_join 节点，获取拼接好的 related_fields1 和 related_fields2
  if (validTargetTypes.includes(sourceNode.type)) {
    const joinConnectedData = sourceProperties.joinConnectedData;
    const connectedData = targetProperties.joinConnectedData || []; //如果connectedData为undefined，初始化为空数组
    let newConnectedData = Array.isArray(connectedData) ? connectedData : [connectedData];
    const index = newConnectedData.findIndex((item) => item.propsDataId === sourceNode.id);
    if (index !== -1) {
      newConnectedData[index] = joinConnectedData;
    } else {
      newConnectedData.push(joinConnectedData);
    }
    targetNode.setProperties({
      ...targetProperties,
      joinConnectedData: newConnectedData,
    });
    targetNode.setProperties({
      ...targetProperties,
      joinConnectedData: newConnectedData,
    });
  }
  if (sourceNode.type == "indicator") {
    const sourceTableName = sourceProperties.tableName;
    const sourceData = sourceProperties.tableData.filter((row: any) => row.isSelected);
    // 将 sourceData 覆盖 targetNode 的对应数据
    const connectedData = targetProperties.connectedData || []; // 如果 connectedData 为 undefined，初始化为空数组
    const newConnectedData = connectedData.map((item: any) => {
      if (item.tableName === sourceTableName) {
        return {
          tableName: sourceTableName,
          data: sourceData,
        };
      }
      return item;
    });
    // 如果没有对应的数据，则添加新数据
    if (!newConnectedData.some((item: any) => item.tableName === sourceTableName)) {
      console.log("源表名称不相同！！！！");
      newConnectedData.push({
        tableName: sourceTableName,
        data: sourceData,
      });
    }

    // 更新 targetNode 的属性
    targetNode.setProperties({
      ...targetProperties,
      connectedData: newConnectedData,
    });
  }
};

async function handleQuery() {
  fieldoptions.value = await IndicatorManageAPI.DataSourceList();
}

// 新增：转换数据的函数
const convertToTreeData = (responseData: any) => {
  return responseData.indicatorList.map((indicator: any) => {
    const children = [];

    if (indicator.indicatorGroups && indicator.indicatorGroups.length > 0) {
      children.push(
        ...indicator.indicatorGroups.map((group: any) => {
          const groupChildren = group.indicators.map((indicator: any) => ({
            id: indicator.id,
            label: indicator.indicatorName,
            disabled: indicator.disabled,
          }));
          return {
            id: group.id,
            label: group.domainName,
            disabled: group.disabled,
            children: groupChildren,
          };
        })
      );
    }

    if (indicator.themeDomains && indicator.themeDomains.length > 0) {
      children.push(
        ...indicator.themeDomains.map((themeDomain: any) => ({
          id: themeDomain.id,
          label: themeDomain.domainName,
          disabled: themeDomain.disabled,
          children: [],
        }))
      );
    }

    return {
      id: indicator.id,
      label: indicator.domainName,
      disabled: indicator.disabled,
      children: children,
    };
  });
};

async function handleChange(id: number) {
  tableListParameter.id = id;
  domainGroupInsertParameter.dataSourceId = id;
  indicatorDomainAPI.SelectDomainTree(domainGroupInsertParameter).then((data) => {
    domainTreeData.value = convertToTreeData(data);
  });
}
const handleDataFetched = (data: any) => {
  console.log(data);
};

const indicatorIds = ref<any[]>();

// 记录树节点ID与LogicFlow节点ID的映射关系
const treeNodeIdToLfNodeId = ref<Map<number, string>>(new Map());

const handleTreeChange = () => {
  if (!lf || !treeRef.value) return;
  // 获取当前所有勾选的树节点ID
  const checkedKeys = treeRef.value.getCheckedKeys();

  // 获取所有已创建的LogicFlow节点ID
  const createdLfNodeIds = Array.from(treeNodeIdToLfNodeId.value.values());

  // 删除未被勾选的节点
  createdLfNodeIds.forEach((lfNodeId) => {
    const treeNodeId = Array.from(treeNodeIdToLfNodeId.value.entries()).find(
      ([_, id]) => id === lfNodeId
    )?.[0];

    if (treeNodeId && !checkedKeys.includes(treeNodeId)) {
      lf.deleteNode(lfNodeId);
      treeNodeIdToLfNodeId.value.delete(treeNodeId);
    }
  });

  indicatorIds.value = [] as number[];

  // 创建新增的勾选节点
  checkedKeys.forEach((treeNodeId: any) => {
    indicatorIds.value!.push(treeNodeId);
    if (!treeNodeIdToLfNodeId.value.has(treeNodeId)) {
      // 找到对应的树节点数据
      const findTreeNode = (data: any[]): any | null => {
        for (const item of data) {
          if (item.id === treeNodeId) return item;
          if (item.children) {
            const result = findTreeNode(item.children);
            if (result) return result;
          }
        }
        return null;
      };

      const treeNode = findTreeNode(domainTreeData.value);
      if (treeNode) {
        // 生成节点位置（这里采用网格布局）
        const index = checkedKeys.indexOf(treeNodeId);
        const row = Math.floor(index / 5); // 每行5个节点
        const col = index % 5;
        const x = 240 + col * 200;
        const y = 100 + row * 150;

        // 创建节点
        const lfNodeId = `indicator-${treeNodeId}`;
        lf.addNode({
          type: "indicator",
          id: lfNodeId,
          x,
          y,
          text: treeNode.label,
          properties: {
            treeNodeId: treeNodeId, // 存储原始树节点ID
            label: treeNode.label,
          },
        });

        // 记录映射关系
        treeNodeIdToLfNodeId.value.set(treeNodeId, lfNodeId);
      }
    }
  });
};

onMounted(() => {
  lf = new LogicFlow({
    container: logicFlowRef.value!,
    grid: true,
    keyboard: {
      enabled: true,
      shortcuts: registerKeyboard(lf, nodeData, settingType),
    },
    textEdit: false,
    // 尝试添加 passive 选项配置
    events: {
      touchmove: {
        passive: false,
      },
      wheel: {
        passive: false,
      },
    },
  });
  handleQuery();
  registeNode(lf);
  initEvent(lf);
  lf.render({});
  lf.translateCenter();
  // 手动禁用 touchmove 和 wheel 事件的 passive 模式
  const container = logicFlowRef.value;
  if (container) {
    const disablePassive = { passive: false };
    container.addEventListener("touchmove", () => {}, disablePassive);
    container.addEventListener("wheel", () => {}, disablePassive);
  }
});
</script>
<style lang="scss" scoped>
.logic-flow-container {
  display: flex;
  width: 100%;
  height: 100%;

  .connection_pool {
    width: 11%;
    height: calc(100% - 0px);

    .indicator_tree {
      height: calc(100% - 20px);
      padding: 0;
      margin: 0;
      overflow: auto; // 确保滚动条生效
    }

    // 可以根据需要调整树节点的样式
    .indicator_tree .el-tree-node {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 20px;
      margin: 10px;
    }

    .el-tree {
      min-width: 200px;
    }
  }

  .logic-flow-header {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    height: 50px;
    padding: 0 20px;
    border-bottom: 1px solid #ccc;
  }

  .logic-flow-main {
    position: relative;
    display: flex;
    width: 80%;
    // height: calc(100% - 54px);
    height: calc(100% - 0px);

    .logic-flow-setting {
      flex-shrink: 0;
      flex-basis: 400px;
      border-left: 1px solid #ccc;
    }

    .logic-flow {
      position: relative;
      flex: 1;
      height: 100%;
    }
  }
}
</style>
